package com.lighthouse.base.common.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.lighthouse.base.common.service.FileManager;
import com.lighthouse.base.common.vo.FileVO;


/*------------------------------------------------------------------------------
 * PROJ : SuperSignElite - W
 * NAME : FileManageController.java
 * DESC : 
 * AUTHOR : hyundong
 * VER  : 0.1
 * Copyright 2010 LG Electronics All rights reserved
 *------------------------------------------------------------------------------
 *                  변         경         사         항                       
 *------------------------------------------------------------------------------
 *  2011.1.3            hyundong    최초생성                                                           
 *----------------------------------------------------------------------------
 */

@Controller
public class FileManageController {
    @Resource (name="FileService")
    private FileManager fileManager;

    protected Log log = LogFactory.getLog(this.getClass());

    @RequestMapping(value = "/storage/getObject.do") //OT=I&OID=098
    public String getObject(HttpServletRequest request, HttpServletResponse response) {
    	boolean bResult;
        String sObjectType=request.getParameter("OT"); //ObjectType
        String sObjectID=request.getParameter("OID"); //ObjectID
       
        try {
        	sObjectType = (sObjectType==null)||(sObjectType.length()<=0) ? "I" : sObjectType;
            if(sObjectType.equals("I")) bResult = getImageByOID(response, sObjectID);
            //if(sObjectType.equals("Z")) bResult = getCompressResult(response, sObjectID);
            if(sObjectType.equals("X")) bResult = getImageByFilename(response, sObjectID);
            if(sObjectType.equals("M")) {
                response.setContentType("video/mpeg");
                bResult = getChunkByFilename(response, sObjectID);
            }
            if(sObjectType.equals("F")) {
                response.setContentType("application/x-shockwave-flash");
                //response.setContentType("video/x-flv");
                bResult = getChunkByFilename(response, sObjectID);
            }
        }
        catch(Exception e) {
            if(log.isDebugEnabled()) log.debug("Error getObject : " + e.toString());
        }
        return null;
    }
    
    public boolean getImageByOID(HttpServletResponse response, String sOID) {
        int nOID = Integer.parseInt(sOID);
        FileVO fileInfo = fileManager.getFileInfo(nOID);
        if((fileInfo==null)||(fileInfo.getFilename().length()<=0)) {
            if(log.isDebugEnabled()) log.debug(String.format("GetImageByOID[%s]--> fileInfo(%s), filename(%s)", sOID, fileInfo==null?"null":fileInfo.getFilename(), fileInfo.getFilename()));
            return false;
        }
        return getImageByFilename(response, fileInfo.getUri()+"/"+fileInfo.getFilename());
    }

    public boolean getImageByFilename(HttpServletResponse response, String sFilename) {
        int nReadByte, nTotalReadByte=0;
        byte[] buffer = new byte[4096];
        ServletOutputStream Output;
        String sStorageBasePath = "C:/LightHouse/Storage";//propertiesService.getString("StorageBasePath"); //"C:/SuperSignWeb/storage";
        String sDefaultErrorImage = "default/DefaultError.png";//propertiesService.getString("DefaultErrorImage"); //"default/DefaultError.png";

        //String sFilename = "C:/SuperSignWeb/storage/mount/바탕화면/nature000.thumbnail.png";// request.getParameter("ID");
        File fromFile = null;
        FileInputStream from = null;

        fromFile = new File(sStorageBasePath + "/" + sFilename);
        if(!fromFile.exists()) { 
            log.debug(String.format("Error:not found File[%s], swap Default Error Image[%s]", sFilename, sDefaultErrorImage));
            fromFile = new File(sStorageBasePath + "/" + sDefaultErrorImage);
            if(!fromFile.exists()) {
                log.debug(String.format("Error:not found Default File[%s]", sDefaultErrorImage));
                return false;
            }
        }
        try {
            Output = response.getOutputStream();
            from = new FileInputStream(fromFile);
            response.setContentType("image/jpeg; charset=utf-8");
            response.addHeader("Content-Length", Long.toString(fromFile.length()));
            while ((nReadByte = from.read(buffer)) != -1) { 
                Output.write(buffer, 0, nReadByte);
                nTotalReadByte += nReadByte;
            }
            log.debug(String.format("getImageFile[%s],size=%d",sFilename,nTotalReadByte));
        }
        catch(Exception e) {
            log.debug(String.format("Error:getTempFile[%s]:%s", sFilename, e.toString()));
        }
        finally {
            try {
                from.close();
            } 
            catch (Exception e) {
                log.debug(String.format("Error:getTempFile[%s]:%s", sFilename, e.toString()));
            }            
        }
        return true;
    }
    
    public boolean getChunkByFilename(HttpServletResponse response, String sOID) {
        int nReadByte, nTotalReadByte=0;
        byte[] buffer = new byte[4096];
        String sFilename="";
        ServletOutputStream Output;
        String sStorageBasePath = "C:/LightHouse/Storage";//propertiesService.getString("StorageBasePath"); //"C:/SuperSignWeb/storage";
        String sDefaultErrorImage = "default/DefaultError.png";//propertiesService.getString("DefaultErrorImage"); //"default/DefaultError.png";

        //String sFilename = "C:/SuperSignWeb/storage/mount/바탕화면/nature000.thumbnail.png";// request.getParameter("ID");
        File fromFile = null;
        FileInputStream from = null;

        try {
            FileVO fileInfo = fileManager.getFileInfo(Integer.parseInt(sOID));
            if((fileInfo==null)||(fileInfo.getFilename().length()<=0)) {
                log.debug(String.format("GetImageByOID[%s]--> fileInfo(%s), filename(%s)", sOID, fileInfo==null?"null":fileInfo.getName(), fileInfo.getFilename()));
                return false;
            }
            sFilename = fileInfo.getUri()+"/"+fileInfo.getFilename();
            response.setHeader("Content-Disposition", "attachment; filename=" + fileInfo.getFilename()); 
        }
        catch(Exception e) {
            return false;
        }
        
        fromFile = new File(sStorageBasePath + "/" + sFilename);
        if(!fromFile.exists()) { 
            log.debug(String.format("Error:not found File[%s]", sFilename));
            return false;
        }
        try {
            response.addHeader("Content-Length", Long.toString(fromFile.length()));
            Output = response.getOutputStream();
            from = new FileInputStream(fromFile);
            while ((nReadByte = from.read(buffer)) != -1) { 
                Output.write(buffer, 0, nReadByte);
                nTotalReadByte += nReadByte;
            }
            log.debug(String.format("getChunkFile[%s],size=%d", sFilename, nTotalReadByte));
        }
        catch(Exception e) {
            log.debug(String.format("Error:getChunkFile:%s",e.toString()));
        }
        finally {
            try {
                from.close();
                fromFile = null;
            } 
            catch (Exception e) {
                log.debug(String.format("Error:getTempFile[%s]:%s", sFilename, e.toString()));
            }            
        }        
        return true;
    }
    
}
